import { createRouter, createWebHistory } from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { useUserStore } from '@/stores/user'

// 路由配置
const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: { title: '登录', requiresAuth: false }
  },
  {
    path: '/',
    component: () => import('@/layout/index.vue'),
    redirect: '/dashboard',
    meta: { requiresAuth: true },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/index.vue'),
        meta: { title: '仪表盘', icon: 'Odometer' }
      },
      {
        path: 'user',
        name: 'User',
        component: () => import('@/views/user/index.vue'),
        meta: { title: '用户管理', icon: 'User' }
      },
      {
        path: 'article',
        name: 'Article',
        component: () => import('@/views/article/index.vue'),
        meta: { title: '文章管理', icon: 'Document' }
      },
      {
        path: 'category',
        name: 'Category',
        component: () => import('@/views/category/index.vue'),
        meta: { title: '分类管理', icon: 'Folder' }
      },
      {
        path: 'tag',
        name: 'Tag',
        component: () => import('@/views/tag/index.vue'),
        meta: { title: '标签管理', icon: 'Collection' }
      },
      {
        path: 'comment',
        name: 'Comment',
        component: () => import('@/views/comment/index.vue'),
        meta: { title: '评论管理', icon: 'ChatDotRound' }
      },
      {
        path: 'album',
        name: 'Album',
        component: () => import('@/views/album/index.vue'),
        meta: { title: '相册管理', icon: 'Picture' }
      },
      {
        path: 'system',
        name: 'System',
        component: () => import('@/views/system/index.vue'),
        meta: { title: '系统管理', icon: 'Setting' },
        children: [
          {
            path: 'config',
            name: 'SystemConfig',
            component: () => import('@/views/system/config/index.vue'),
            meta: { title: '系统配置', icon: 'Setting' }
          },
          {
            path: 'role',
            name: 'SystemRole',
            component: () => import('@/views/system/role/index.vue'),
            meta: { title: '角色管理', icon: 'Avatar' }
          },
          {
            path: 'permission',
            name: 'SystemPermission',
            component: () => import('@/views/system/permission/index.vue'),
            meta: { title: '权限管理', icon: 'Key' }
          },
          {
            path: 'monitor',
            name: 'SystemMonitor',
            component: () => import('@/views/system/monitor/index.vue'),
            meta: { title: '系统监控', icon: 'Monitor' }
          },
          {
            path: 'log',
            name: 'SystemLog',
            component: () => import('@/views/system/log/index.vue'),
            meta: { title: '系统日志', icon: 'Document' }
          },
          {
            path: 'login-log',
            name: 'LoginLog',
            component: () => import('@/views/system/login-log/index.vue'),
            meta: { title: '登录日志', icon: 'User' }
          },
          {
            path: 'job',
            name: 'SystemJob',
            component: () => import('@/views/system/job/index.vue'),
            meta: { title: '定时任务', icon: 'Clock' }
          },
          {
            path: 'backup',
            name: 'SystemBackup',
            component: () => import('@/views/system/backup/index.vue'),
            meta: { title: '数据备份', icon: 'Download' }
          }
        ]
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/profile/index.vue'),
        meta: { title: '个人资料', icon: 'User', hidden: true }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/error/404.vue'),
    meta: { title: '404' }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 管理后台` : '管理后台'
  
  const userStore = useUserStore()
  
  // 检查是否需要登录验证
  if (to.meta.requiresAuth !== false) {
    // 检查是否已登录
    if (!userStore.isLoggedIn) {
      // 未登录，跳转到登录页
      next('/login')
      return
    }
    
    // 已登录但没有用户信息，尝试获取用户信息
    if (!userStore.userInfo.id) {
      try {
        await userStore.initUserInfo()
      } catch (error) {
        console.error('获取用户信息失败:', error)
        // 获取用户信息失败，清除token并跳转到登录页
        userStore.resetUserInfo()
        next('/login')
        return
      }
    }
  }
  
  // 如果已登录且访问登录页，跳转到首页
  if (to.path === '/login' && userStore.isLoggedIn) {
    next('/')
    return
  }
  
  next()
})

router.afterEach(() => {
  NProgress.done()
})

export default router
